package com.cbb.display.controller;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.cbb.display.entity.Region;
import com.cbb.display.service.RegionService;
import com.cbb.display.util.CommonUtil;
import com.cbb.display.enums.ErrorEnum;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bigbomb
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/region")
public class RegionController {
	@Autowired
	private RegionService regionService;

	   @GetMapping("/list")
		public JSONObject list() {
		List<Region> funnelList = regionService.list();
		return CommonUtil.successJson(funnelList);
			
		}



		@PostMapping("/add")
	    public JSONObject add(String regionformlist) {
			List<Region>  idcollection = new ArrayList<Region>();
			List<Region>  noidcollection =new ArrayList<Region>();
			List<Region>  collection = JSONObject.parseArray(regionformlist, Region.class);
			for(Region funnel : collection)
			{
				if(funnel.getId()== null )
				{
					noidcollection.add(funnel);
				}
				else {
					idcollection.add(funnel);
				}
			}
			boolean status = regionService.addRegion(noidcollection,idcollection);
		    
		    if(status)
		    {
		    	return CommonUtil.successJson();
		    }
		    else {
				return CommonUtil.errorJson(ErrorEnum.E_500);
			}
	   }
		
		@PostMapping("/update")
	    public JSONObject update(String region) {
			Region goodObject = JSONObject.parseObject(region,Region.class);
	        boolean status = regionService.updateById(goodObject);
		    if(status)
		    {
		    	return CommonUtil.successJson();
		    }
		    else {
				return CommonUtil.errorJson(ErrorEnum.E_500);
			 }
			}
		
		@PostMapping("/del")
	    public JSONObject del(Long id) {
	    boolean status = regionService.removeById(id);
	    if(status)
	    {
	    	return CommonUtil.successJson();
	    }
	    else {
			return CommonUtil.errorJson(ErrorEnum.E_500);
		}
	    	
	    }
}
